/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) RsaCipherApi.java 2018-08-06 17:26
 */

package cn.jh.common.core.crypto;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;


/**
 * 基于JCA体系的 `AsymmetricCipherApi` 接口的RSA加密算法实现。
 *
 * @author Fuchun
 * @since 1.0
 */
public class RsaCipherApi extends BaseAsymmetricCipherApi {

    private static final RsaCipherApi DEFAULT_API = new RsaCipherApi(KeyBit.KB_1024.bit);

    /**
     * 默认的 {@code RsaCipherApi} 实例。
     * <pre>
     * 1. transformation: AES/ECB/PKCS1Padding
     * 2. key size: 1024
     * 3. signature: SHA1withRSA
     * </pre>
     * 密钥大小为 1024，签名算法为 {@code SHA1withRSA}。
     */
    public static RsaCipherApi getInstance() {
        return DEFAULT_API;
    }

    public static RsaCipherApi getInstance(int keySize, String signatureAlgorithm) {
        return new RsaCipherApi(keySize, signatureAlgorithm);
    }

    /**
     * 构造新的默认签名算法为 {@code SHA1withRSA}，指定密钥大小的 {@code RsaCipherApi}。
     *
     * @param keySize 密钥大小（bit）。
     */
    public RsaCipherApi(int keySize) {
        this(keySize, "SHA1withRSA");
    }

    /**
     * 构造新的指定密钥大小和签名算法的 {@code RsaCipherApi}。
     *
     * @param keySize 密钥大小（bit）。
     * @param signatureAlgorithm 私钥签名算法名称，如：SHA1withRSA, SHA256withRSA
     */
    public RsaCipherApi(int keySize, String signatureAlgorithm) {
        super(CipherParamsKt.rsaBuilder()
                .setKeySize(keySize)
                .setSignatureAlgorithm(signatureAlgorithm)
                .build());
    }

    public RsaCipherApi(AsymmetricCipherParams params) {
        super(params);
    }

    @Override
    public RSAPublicKey toPublicKey(byte[] key) throws CryptoException, IllegalArgumentException {
        return (RSAPublicKey) super.toPublicKey(key);
    }

    @Override
    public RSAPrivateKey toPrivateKey(byte[] key) throws CryptoException, IllegalArgumentException {
        return (RSAPrivateKey) super.toPrivateKey(key);
    }
}
